package com.thinkit.nosql.aspect;

import com.thinkit.nosql.annotation.CacheClear;
import com.thinkit.nosql.base.BaseRedisService;
import com.thinkit.utils.utils.Checker;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class CacheClearAspect {

    @Autowired
    BaseRedisService baseRedisService;

    @AfterReturning("execution(* com.thinkit..*.*(..)) && @annotation(com.thinkit.nosql.annotation.CacheClear)")
    public void process(JoinPoint joinPoint) throws Throwable {
        Object target = joinPoint.getTarget();
        Class<?>  targetClass = target.getClass();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Object[] args = joinPoint.getArgs();
        CacheClear cacheClear = method.getAnnotation(CacheClear.class);
        String finalKey = new ResolvingKey(targetClass,method,cacheClear).args(args).resolve();
        clearCache(finalKey);
    }

    private void clearCache(String key){
        if(key.contains("|")){
            String[] keys = key.split("\\|");
            if(Checker.BeNotEmpty(keys)){
                for(String k: keys){
                    if(Checker.BeNotBlank(k)){
                        clearKey(k);
                    }
                }
            }
        }else{
            clearKey(key);
        }
    }

    private void clearKey(String key){
        if(Checker.BeNotNull(key)){
            if(key.endsWith("*")){
                baseRedisService.removeBlear(key);
            }else{
                baseRedisService.remove(key);
            }
        }
    }



}
